package com.llxwz.controller;


import com.llxwz.entity.User;
import com.llxwz.service.UserService;
import com.llxwz.util.CommunityConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;

import java.util.Map;

@Controller
public class RegisterController implements CommunityConstant {

    @Autowired
    UserService userService;

    @GetMapping("/register")
    public String toRegister(){
        return "site/register";
    }

    @PostMapping("/register")
    public String register(Model model, User user){
        Map<String, Object> map = userService.register(user);

        //map为空表示注册成功，但还没有激活，所以先不能直接进入首页，
        // 需要中转站网页，得提示还没有激活
        if(map == null || map.isEmpty()){
            model.addAttribute("msg","注册成功,已经向你的邮箱发送了激活码");
            model.addAttribute("target","/index");
            return "site/operate-result";

        }else{//注册有误，返回注册页面并携带错误信息
            model.addAttribute("usernameMsg",map.get("usernameMsg"));
            model.addAttribute("passwordMsg",map.get("passwordMsg"));
            model.addAttribute("emailMsg",map.get("emailMsg"));
            return "site/register";
        }

    }


    //这是发送邮件里的url
    //http://localhost:8088/forum/activation/id/激活码
    @GetMapping("/activation/{id}/{code}")
    public String activation(Model model, @PathVariable("id")int id,@PathVariable("code")String code){
        int result = userService.activation(id, code);
        if(result == ACTIVATION_SUCCESS){
            model.addAttribute("msg","激活成功,您的账号已经登陆了");
            model.addAttribute("target","/login");
        }else if (result == ACTIVATION_REPEAT){
            model.addAttribute("msg","你的账号已经激活过了");
            model.addAttribute("target","/index");
        }else{
            model.addAttribute("msg","激活失败,您提供的激活码不正确");
            model.addAttribute("target","/index");
        }
        //跳入中转页面，提示用户信息
        return "site/operate-result";
    }

}
